<?php
/*
* Author: Jason ZHENG <zmj522008@hotmil.com>
* Date  : 2018/06/01
* Class : OperationLog 操作日志
*/

namespace app\index\controller\Log;
use think\Db;

class OperationLog
{

	public static function get_table_name()
	{
		return 'operation_log';
	}

	public static function insert($data)
	{
		$validate = self::validate($data);
		if($validate === true)
		{
			if (array_key_exists('operation_time', $data)) {
				$data['operation_time'] = date('Y-m-d H:i:s',time());
			}else{
				$data = array_merge($data, ['operation_time' => date('Y-m-d H:i:s',time())]);
			}

			if (array_key_exists('ip', $data)) {
				$data['ip'] = self::get_ip_address();
			}else{
				$data = array_merge($data, ['ip' => self::get_ip_address()]);
			}

			Db::table(self::get_table_name())->insert($data);
			return true;
		}else{
			return $validate;
		}
		
	}

	public static function validate($data)
	{
		if(! array_key_exists('user_id', $data))
			return 'error: user_id not found';
		if(! array_key_exists('module', $data))
			return 'error: module not found';
		if(! array_key_exists('module_id', $data))
			return 'error: module_id not found';
		if(! array_key_exists('operation_type', $data))
			return 'error: opration_type not found';
		if(! array_key_exists('operation_content', $data))
			return 'error: operation_content not found';

		return true;
	}

	public static function get_ip_address()
	{ 
		if(getenv('HTTP_CLIENT_IP')) {
		  $onlineip = getenv('HTTP_CLIENT_IP');
		} elseif(getenv('HTTP_X_FORWARDED_FOR')) {
		  $onlineip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif(getenv('REMOTE_ADDR')) {
		  $onlineip = getenv('REMOTE_ADDR');
		} else {
		  $onlineip = $HTTP_SERVER_VARS['REMOTE_ADDR'];
		}
		return $onlineip;
	}
}